package com.ruoyi.erecord.locus.logic;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.tools.enums.DeviceTypeEnum;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.erecord.locus.domain.Locus;
import com.ruoyi.erecord.locus.domain.LocusSyncRecord;
import com.ruoyi.erecord.locus.domain.bo.LocusBo;
import com.ruoyi.erecord.locus.domain.vo.LocusSyncVo;
import com.ruoyi.erecord.locus.domain.vo.LocusVo;
import com.ruoyi.erecord.locus.mapper.LocusMapper;
import com.ruoyi.erecord.locus.mapper.LocusStateMapper;
import com.ruoyi.erecord.locus.mapper.LocusSyncRecordMapper;
import com.ruoyi.erecord.locus.service.ILocusService;
import com.ruoyi.stat.toilet.logic.HttpLogic;
import com.ruoyi.system.service.ISysConfigService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Optional;

@Slf4j
@Service
@RequiredArgsConstructor
public class LocusDataService {
    private final ISysConfigService configService;
    private final LocusMapper locusMapper;
    private final LocusSyncRecordMapper baseMapper;

    @Async
    public void updateProcess() {
        //获取最后一次同步记录数据
        LocusSyncRecord record = baseMapper.getLastSyncData();
        if(Optional.ofNullable(record).isPresent()){
            //存在 判断同步结果
            //同步成功，则获取时间节点，根据节点获取这次需要同步数据
            if(record.getCode()==0){
                getLocusData(record.getLast_gps_time(),0);
            }else {
                //同步失败，重试3次
                if(record.getRetry()>=3){
                    getLocusData(record.getLast_gps_time(),0);
                }else {
                    String content = record.getContent();
                    JSONArray arr = JSONUtil.parseArray(content);
                    List<LocusSyncVo> list = arr.toList(LocusSyncVo.class);
                    postData(list, record.getLast_gps_time(), record.getRetry());
                }
            }
        }
        else{
            //初次开始同步
            getLocusData(null,0);
        }
    }

    //根据节点获取当前同步数据
    private void getLocusData(Date gpsTime,Integer retry){
        Locus bo=new Locus();
        bo.setDeviceType(DeviceTypeEnum.USER.getCode());
        if(gpsTime!=null)
            bo.setGpsTime(gpsTime);
        List<Locus> _list = locusMapper.querySyncData(bo);

        //若有数据，则进行转换为同步接口数据
        if(Optional.ofNullable(_list).isPresent() && _list.size()>0){
            List<LocusSyncVo> track_list = new ArrayList<>();
            for(Locus item:_list){
                LocusSyncVo obj = new LocusSyncVo();
                obj.setTrack_id(item.getId());
                obj.setDevice_id(item.getDeviceCode());
                obj.setLongitude(item.getPointx().toString());
                obj.setLatitude(item.getPointy().toString());
                obj.setLoc_time(DateUtils.parseDateToStr("yyyy-MM-dd HH:mm:ss",item.getGpsTime()));
                obj.setGps_power(item.getPowerLevel().intValue());
                obj.setGps_signal(item.getGsmLevel().intValue());
                track_list.add(obj);
            }
            //获取同步节点
            gpsTime = _list.get(_list.size()-1).getGpsTime();
            postData(track_list,gpsTime,retry);
        }
    }

     private void postData(List<LocusSyncVo> track_list,Date gpsTime,Integer retry){

        //同步数据
        JSONObject params = JSONUtil.createObj();
        params.set("track_list", track_list);
        String url = "/workspace/elec/gps/track";
        String resp = HttpLogic.postBody(configService, url, params.toString());
         log.info("----sync return data:"+resp);
        JSONObject json = JSONUtil.parseObj(resp);
        int code = json.getInt("code");

        //同步结果记录
         LocusSyncRecord syncRecord = new LocusSyncRecord();
//         syncRecord.setCreateTime(new Date());
//         syncRecord.setPage_num(pageNum);
//         syncRecord.setPage_size(pageSize);
         syncRecord.setContent(JSONUtil.toJsonStr(track_list));
//         syncRecord.setUpdateTime(gpsTime);
         syncRecord.setCode(code);
         syncRecord.setLast_gps_time(gpsTime);
         syncRecord.setRetry(retry+1);

         if (code != 0) {
             String msg=json.getStr("msg");
             syncRecord.setMsg(msg);
            log.info("sync locus data api error:"+msg);
         }
         baseMapper.insert(syncRecord);
    }
}
